package com.designoutput.ui.editors.transformEditorClasses
{
	import com.designoutput.utils.MathUtils;
	
	import flash.geom.Point;

	public class TransformUtils
	{
		public static function get3PointsTransformation(points:Vector.<Point>):TransformationInfo {
			var topLeft:Point = points[0];
			var topRight:Point = points[1];
			var bottomLeft:Point = points[2];
			
			var topOffset:Point = topRight.subtract(topLeft);
			var leftOffset:Point = bottomLeft.subtract(topLeft);
			
			var skewYRadians:Number = Math.atan2(topOffset.y, topOffset.x);
			var skewY:Number = MathUtils.radianToDegrees(skewYRadians);
			
			var skewXRadians:Number = Math.atan2(leftOffset.y, leftOffset.x) - Math.PI/2;
			var skewX:Number = MathUtils.radianToDegrees(skewXRadians);
			
			skewX = MathUtils.round(skewX, 2);
			skewY = MathUtils.round(skewY, 2);
			
			var transformationInfo:TransformationInfo = new TransformationInfo();
			
			transformationInfo.x = topLeft.x;
			transformationInfo.y = topLeft.y;
			
			transformationInfo.width = topOffset.length;
			transformationInfo.height = leftOffset.length;
			
			transformationInfo.scaleX = 1;
			transformationInfo.scaleY = 1;
			
			if(skewY == skewX){				
				transformationInfo.skewX = 0;
				transformationInfo.skewY = 0;
				transformationInfo.rotation = skewX;
			} else {
				transformationInfo.skewX = skewX;
				transformationInfo.skewY = skewY;
				transformationInfo.rotation = 0;
			}
			
			return transformationInfo;
		}
		
		public static function transformToCommonSkew(transformationInfo:TransformationInfo):TransformationInfo {
			if(transformationInfo.skewX == 0 && transformationInfo.skewY == 0)
				return transformationInfo;
			
			var skewXRadians:Number = MathUtils.degreesToRadian(transformationInfo.skewX);
			var skewYRadians:Number = MathUtils.degreesToRadian(transformationInfo.skewY);
			
			var sx:Number = Math.cos(skewYRadians);
			var sky:Number = Math.sin(skewYRadians);
			var skx:Number = -Math.sin(skewXRadians);
			var sy:Number = Math.cos(skewXRadians);
			
			var ti:TransformationInfo = transformationInfo.clone();
			
			ti.width = transformationInfo.width/sx;
			ti.height = transformationInfo.height/sy;
			ti.skewX = MathUtils.radianToDegrees(skx);
			ti.skewY = MathUtils.radianToDegrees(sky);
			ti.scaleX = sx;
			ti.scaleY = sy;
			ti.rotation = 0;
			
			return ti;
		}
	}
}